// app.js

console.log('wx object available:', typeof wx !== 'undefined');

// 导入 mockUtils，用于接管 API 请求
const { mockRequest, MOCK_BASE_URL } = require('./utils/mockUtils');

// 💡 【重要】设置开关：将此变量设置为 true 即可启用 Mock
const isMock = true; 

App({
  globalData: {
    userInfo: null,
    inviterID: null,
    isLoggingIn: false,
    loginPromise: null,
    loginTime: 0,
    // 💡 新增全局变量，标识是否处于 Mock 状态
    isMocking: isMock 
  },

  onLaunch: function (options) {
    console.log('onLaunch 开始，options:', options || '无参数');
    options = options || {};
    this.globalData.inviterID = options.query?.inviterID || options.inviterID || '';
    console.log('设置后的启动参数:', options);
    console.log('全局存储 inviterID:', this.globalData.inviterID);

    // 💡 【关键修改】如果 isMock 为 true，则替换掉 wx.request 并模拟登录
    if (isMock) {
        console.warn('============= 启用 MOCK 模式 =============');
        // 保存原生 request，并替换为 mockRequest
        this.globalData.originalRequest = wx.request;
        wx.request = mockRequest;
        
        // 模拟登录成功，跳过实际的 doAutoLogin
        const mockUserInfo = { 
            role: 'expert_learner', 
            name: 'Mock User',
            openID: 'mock_openid_123',
            unionID: 'mock_unionid_123',
            jwt_token: 'mock_jwt_token_123',
        };
        this.globalData.loginTime = Date.now();
        this.globalData.userInfo = mockUserInfo;
        
        // 写入必要的缓存信息
        wx.setStorageSync('jwt_token', mockUserInfo.jwt_token);
        wx.setStorageSync('role', mockUserInfo.role);
        wx.setStorageSync('openID', mockUserInfo.openID);
        wx.setStorageSync('unionID', mockUserInfo.unionID);
        
        this.globalData.loginPromise = Promise.resolve(this.globalData.userInfo);
        this.globalData.isLoggingIn = false;
        
        console.log('已模拟登录状态和用户信息。');

        // 在 Mock 模式下，直接调用 checkNewUser
        this.checkNewUser();
    } else {
        console.log('执行静默登录');
        this.doAutoLogin(true);
    }
  },

  doAutoLogin(shouldRefresh = false, retryCount = 0) {
    if (isMock && this.globalData.loginPromise) {
        // Mock 模式下，直接返回已解决的 Promise
        return this.globalData.loginPromise;
    }
    
    // --- 原代码的静默登录逻辑 ---
    const now = Date.now();
    shouldRefresh = shouldRefresh || (now - this.globalData.loginTime) > 3600000;

    if (this.globalData.isLoggingIn && !shouldRefresh) {
      console.log('已有登录进行中，返回现有 Promise');
      return this.globalData.loginPromise;
    }

    console.log('doAutoLogin called, retryCount:', retryCount, 'shouldRefresh:', shouldRefresh);
    this.globalData.isLoggingIn = true;
    this.globalData.loginPromise = new Promise((resolve, reject) => {
      if (retryCount >= 3) {
        console.error('达到最大重试次数，登录失败');
        wx.showToast({
          title: '登录失败，请稍后重试',
          icon: 'none',
          duration: 3000
        });
        this.globalData.isLoggingIn = false;
        reject(new Error('Max retries reached'));
        // 延迟后再次尝试静默登录
        setTimeout(() => {
          this.doAutoLogin(true, 0).then(resolve).catch(reject);
        }, 5000); // 延迟 5 秒后重试
        return;
      }

      const openID = wx.getStorageSync('openID');
      const jwtToken = wx.getStorageSync('jwt_token');
      if (openID && jwtToken && retryCount === 0 && !shouldRefresh) {
        console.log('已有 openID:', openID, 'jwtToken:', jwtToken.slice(0, 10) + '****');
        wx.request({
          // 💡 使用 MOCK_BASE_URL 变量
          url: `${MOCK_BASE_URL}/user/settings?openID=${encodeURIComponent(openID)}`,
          method: 'GET',
          header: { 'Authorization': `Bearer ${jwtToken}` },
          success: (res) => {
            console.log('token 验证响应状态码:', res.statusCode);
            console.log('token 验证响应数据:', JSON.stringify(res.data, null, 2));
            if (res.statusCode === 200 && res.data.openID) {
              console.log('token 有效，用户信息:', res.data);
              this.globalData.userInfo = res.data;
              this.globalData.loginTime = Date.now();
              wx.setStorageSync('openID', res.data.openID);
              wx.setStorageSync('unionID', res.data.unionID || '');
              wx.setStorageSync('jwt_token', res.data.jwt_token || jwtToken);
              wx.setStorageSync('role', res.data.role || '');
              this.globalData.isLoggingIn = false;
              resolve(res.data);
            } else {
              console.error('token 无效:', {
                statusCode: res.statusCode,
                response: res.data,
                errorDetail: res.data?.detail || '未知错误'
              });
              this.wechatLogin(retryCount, resolve, reject);
            }
          },
          fail: (err) => {
            console.error('token 验证请求失败:', err);
            this.wechatLogin(retryCount, resolve, reject);
          }
        });
      } else {
        this.wechatLogin(retryCount, resolve, reject);
      }
    });
    return this.globalData.loginPromise;
  },

  wechatLogin(retryCount, resolve, reject) {
    console.log('执行微信登录');
    wx.login({
      success: (res) => {
        if (res.code) {
          console.log('获取微信 code:', res.code);
          wx.request({
            // 💡 使用 MOCK_BASE_URL 变量
            url: `${MOCK_BASE_URL}/user/wechat-login`,
            method: 'POST',
            data: {
              code: res.code,
              inviterID: wx.getStorageSync('inviterID') || this.globalData.inviterID
            },
            header: { 'Content-Type': 'application/json' },
            success: (res) => {
              console.log('微信登录响应状态码:', res.statusCode);
              //console.log('微信登录响应数据:', JSON.stringify(res.data, null, 2));
              if (res.statusCode === 200) {
                const openID = res.data.openID || res.data.openId || res.data.data?.openID;
                const unionID = res.data.unionID || res.data.unionId || res.data.data?.unionID;
                const jwt_token = res.data.jwt_token || res.data.jwtToken || res.data.token || res.data.data?.jwt_token;
                const role = res.data.role || res.data.data?.role;
                if (openID && jwt_token) {
                  console.log('登录成功，存储用户信息', { openID, unionID, jwt_token, role });
                  wx.setStorageSync('openID', openID);
                  wx.setStorageSync('unionID', unionID || '');
                  wx.setStorageSync('jwt_token', jwt_token);
                  wx.setStorageSync('role', role || '');
                  this.globalData.userInfo = res.data;
                  this.globalData.loginTime = Date.now();

                  wx.request({
                    // 💡 使用 MOCK_BASE_URL 变量
                    url: `${MOCK_BASE_URL}/user/settings?openID=${encodeURIComponent(openID)}`,
                    method: 'GET',
                    header: { 'Authorization': `Bearer ${jwt_token}` },
                    success: (verifyRes) => {
                      if (verifyRes.statusCode === 200) {
                        console.log('新 token 有效', verifyRes.data);
                        this.globalData.isLoggingIn = false;
                        resolve(res.data);
                      } else {
                        console.error('新 token 无效:', {
                          statusCode: verifyRes.statusCode,
                          response: verifyRes.data,
                          errorDetail: verifyRes.data?.detail || '未知错误'
                        });
                        setTimeout(() => {
                          this.doAutoLogin(false, retryCount + 1).then(resolve).catch(reject);
                        }, 2000); // 延迟 2 秒重试
                      }
                    },
                    fail: (err) => {
                      console.error('验证新 token 失败:', err);
                      setTimeout(() => {
                        this.doAutoLogin(false, retryCount + 1).then(resolve).catch(reject);
                      }, 2000);
                    }
                  });
                } else {
                  console.error('微信登录失败: 缺少必要字段', {
                    hasOpenID: !!openID,
                    hasJwtToken: !!jwt_token,
                    responseData: res.data
                  });
                  setTimeout(() => {
                    this.doAutoLogin(false, retryCount + 1).then(resolve).catch(reject);
                  }, 2000);
                }
              } else {
                console.error('微信登录失败: 状态码异常', {
                  statusCode: res.statusCode,
                  responseData: res.data,
                  errorDetail: res.data?.detail || '未知错误'
                });
                setTimeout(() => {
                  this.doAutoLogin(false, retryCount + 1).then(resolve).catch(reject);
                }, 2000);
              }
            },
            fail: (err) => {
              console.error('微信登录请求失败:', err);
              setTimeout(() => {
                this.doAutoLogin(false, retryCount + 1).then(resolve).catch(reject);
              }, 2000);
            }
          });
        } else {
          console.error('wx.login 失败:', res.errMsg);
          setTimeout(() => {
            this.doAutoLogin(false, retryCount + 1).then(resolve).catch(reject);
          }, 2000);
        }
      },
      fail: (err) => {
        console.error('wx.login 调用失败:', err);
        setTimeout(() => {
          this.doAutoLogin(false, retryCount + 1).then(resolve).catch(reject);
        }, 2000);
      }
    });
  },

  ensureValidToken() {
    return new Promise((resolve, reject) => {
      const jwtToken = wx.getStorageSync('jwt_token');
      const openID = wx.getStorageSync('openID');
      if (!jwtToken || !openID) {
        console.log('本地没有有效token，执行登录流程');
        return this.doAutoLogin(true).then(resolve).catch(reject);
      }
      const now = Date.now();
      const shouldRefresh = (now - this.globalData.loginTime) > 3600000;
      if (shouldRefresh) {
        console.log('Token可能已过期，执行登录刷新');
        return this.doAutoLogin(true).then(resolve).catch(reject);
      }
      console.log('使用现有token');
      resolve(this.globalData.userInfo || {});
    });
  },

  safeSwitchTab: function (url) {
    this.ensureValidToken().then(() => {
      wx.switchTab({
        url,
        success: () => console.log(`跳转到 ${url} 成功`),
        fail: (err) => {
          console.error(`跳转到 ${url} 失败:`, err);
          wx.showToast({ title: '跳转失败，请重试', icon: 'none' });
        }
      });
    }).catch(err => {
      console.error('token验证失败，无法跳转:', err);
      wx.showToast({ title: '登录状态异常，请重试', icon: 'none' });
    });
  },

  safeNavigateTo: function (url) {
    this.ensureValidToken().then(() => {
      wx.navigateTo({
        url,
        success: () => console.log(`跳转到 ${url} 成功`),
        fail: (err) => {
          console.error(`跳转到 ${url} 失败:`, err);
          wx.showToast({ title: '跳转失败，请重试', icon: 'none' });
        }
      });
    }).catch(err => {
      console.error('token验证失败，无法跳转:', err);
      wx.showToast({ title: '登录状态异常，请重试', icon: 'none' });
    });
  },

  checkNewUser: function () {
    const role = wx.getStorageSync('role') || '';
    if (this.globalData.inviterID) {
      console.log('存在 inviterID，跳转到 conversation');
      this.safeSwitchTab('/pages/conversation/conversation');
    } else if (!role) {
      console.log('检测到新用户，跳转到 role 页面');
      this.safeNavigateTo('/pages/role/role');
    } else {
      console.log('检测到老用户，不强制跳转');
    }
  },
  
  // 💡 新增：统一获取 API 基地址的函数
  getApiBaseUrl() {
    return MOCK_BASE_URL;
  }
});